import request from "@/utils/request.js";
import { logout } from "@/utils/auth.js";
import { getToken } from "@/utils/auth.js";

// 文件上传
// api/common/index.js
export function uploadFile(filePath) {
  return new Promise((resolve, reject) => {
    const upload = (retry = false) => {
      uni.uploadFile({
        url: "http://localhost:8080/file/upload",
        filePath,
        name: "file",
        header: {
          "Content-Type": "multipart/form-data",
          Authorization: `Bearer ${getToken()}`,
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.success) {
              resolve(data.data); // 确保返回data.data
            } else {
              reject(new Error(data.message || "上传失败"));
            }
          } catch (e) {
            reject(new Error("解析响应数据失败"));
          }
        },
        fail: (err) => {
          if (err.statusCode === 401 && !retry) {
            request
              .refreshToken()
              .then((token) => {
                upload(true); // 重试上传
              })
              .catch(() => {
                logout();
                uni.navigateTo({ url: "/pages/login/login" });
                reject(err);
              });
          } else {
            reject(err);
          }
        },
      });
    };
    upload();
  });
}
